import { observable, computed, IObservableArray } from 'mobx';
import BookStore from '../stores/BookStore'
import { uuid } from '../utils';

export interface IBook {
  bookName: string;
  url?: string;
  star: number;
  tags?: string[];
}
export default class BookModel {
  public static fromJS(store: BookStore, book: IBook) {
    return new BookModel(store, book);
  }

  public id: string;
  @observable public url?: string;
  @observable public bookName: string;
  @observable public star: number;
  @observable public tags: IObservableArray<string> = observable.array([]);
  private store: BookStore;

  @computed get tagStr(): string {
    return this.tags.join(' ')
  }
  constructor(store: BookStore, book: IBook) {
    this.store = store;
    this.id = uuid();
    this.bookName = book.bookName;
    this.url = book.url
    this.star = book.star;
    if (book.tags) {
      this.tags = observable.array(book.tags)
    }
  }

  public rate(num: number) {
    this.star = num;
  }

  public destroy() {
    this.store.decTag(this.tags)
    this.store.books.remove(this);
  }

  public change(bookName: string, url?: string) {
    this.bookName = bookName;
    this.url = url
  }
  public changeTag(tags: string) {
    const arr = tags.split(' ').filter(v => v.trim())
    const olds = new Set(this.tags)
    const newTag = arr.filter(v => !olds.has(v))
    const deleteTag = this.tags.filter(v => arr.indexOf(v) === -1)
    this.store.incTag(newTag)
    this.store.decTag(deleteTag)
    this.tags = observable.array(arr);
  }

  public toJS(): IBook {
    return {
      bookName: this.bookName,
      star: this.star,
      url: this.url,
      tags: this.tags.slice()
    };
  }
}
